package com.cmc.cloud.cmclink.doc.rpcservice.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import com.cmc.cloud.cmclink.svl.api.base.req.*;import com.cmc.cloud.cmclink.svl.api.base.resp.BargePolAndPodRespDTO;import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import com.cmc.cloud.cmclink.bdt.api.base.TerminalApi;
import com.cmc.cloud.cmclink.bdt.api.base.dto.req.TerminalListByCodeReqDTO;
import com.cmc.cloud.cmclink.bdt.api.base.dto.req.TerminalListByPortCodeReqDTO;
import com.cmc.cloud.cmclink.bdt.api.base.dto.resp.TerminalListByCodeRespDTO;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.ApiErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.constants.errorconstant.TerminalDgTeuLimitedErrorCodeConstants;
import com.cmc.cloud.cmclink.doc.rpcservice.TerminalTransferService;
import com.cmc.cloud.cmclink.svl.api.base.BargeRotationApi;
import com.cmc.cloud.cmclink.svl.api.base.resp.BargeRotationRespVO;
import com.cmc.cloud.cmclink.svl.api.base.resp.TransportValidateRespDTO;
import com.cmes.framework.common.exception.util.ServiceExceptionUtil;
import com.cmes.framework.common.pojo.CommonResult;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 港口基础数据转换
 * 
 * @author dev89
 * @date 2025/07/18 09:07
 **/
@Service
@Validated
@Slf4j
public class TerminalTransferServiceImpl implements TerminalTransferService {

    @Resource
    private TerminalApi terminalApi;

    @Resource
    private BargeRotationApi bargeRotationApi;

    @Override
    public List<TerminalListByCodeRespDTO> queryTerminalByCode(List<String> terminalCode) {
        if (CollectionUtils.isEmpty(terminalCode)) {
            return Collections.emptyList();
        }
        TerminalListByCodeReqDTO reqDTO = new TerminalListByCodeReqDTO(terminalCode);
        CommonResult<List<TerminalListByCodeRespDTO>> commonResult;
        try {
            commonResult = terminalApi.listByCodeList(reqDTO);
        } catch (Exception e) {
            throw ServiceExceptionUtil
                .exception(TerminalDgTeuLimitedErrorCodeConstants.TERMINAL_QUERY_NAME_BY_CODE_API);
        }
        if (commonResult == null || CollectionUtil.isEmpty(commonResult.getData())) {
            log.error("通过港口编码获取基础数据失败， 港口编码：{}", Arrays.toString(terminalCode.toArray()));
            return Collections.emptyList();
        } else {
            return commonResult.getData();
        }
    }

    @Override
    public List<TerminalListByCodeRespDTO> queryTerminalByPortCode(String portCode) {
        TerminalListByPortCodeReqDTO reqDto = new TerminalListByPortCodeReqDTO();
        reqDto.setPortCode(portCode);
        CommonResult<List<TerminalListByCodeRespDTO>> commonResult;
        try {
            commonResult = terminalApi.listByPortCodeList(reqDto);
        } catch (Exception e) {
            log.error("caught an exception on queryTerminalByPortCode", e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_TERMINAL_BY_PORT_CODE_EXCEPTION);
        }
        if (commonResult == null || CollectionUtil.isEmpty(commonResult.getData())) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_TERMINAL_BY_PORT_CODE_EMPTY);
        }
        return commonResult.getData();
    }

    @Override
    public boolean existBargeRotation(String bargeType, String vesselCode, String portCode, String voyageEx,
        String voyageIm) {
        CommonResult<List<BargeRotationRespVO>> commonResult =
            queryBargeRotation(bargeType, vesselCode, portCode, voyageEx, voyageIm);
        return commonResult != null && !CollectionUtil.isEmpty(commonResult.getData());
    }

    @Override
    public BargeRotationRespVO getBargeRotation(String bargeType, String vesselCode, String portCode, String voyageEx,
        String voyageIm) {
        CommonResult<List<BargeRotationRespVO>> commonResult =
            queryBargeRotation(bargeType, vesselCode, portCode, voyageEx, voyageIm);
        if (commonResult == null || CollectionUtil.isEmpty(commonResult.getData())) {
            return null;
        }
        return commonResult.getData().get(0);
    }

    private CommonResult<List<BargeRotationRespVO>> queryBargeRotation(String bargeType, String vesselCode,
        String portCode, String voyageEx, String voyageIm) {
        BargeQueryReqDTO bargeQueryReqDTO = new BargeQueryReqDTO();
        bargeQueryReqDTO.setBargeType(bargeType);
        bargeQueryReqDTO.setTransportCode(vesselCode);
        bargeQueryReqDTO.setPortCode(portCode);
        bargeQueryReqDTO.setExVoy(voyageEx);
        bargeQueryReqDTO.setImVoy(voyageIm);
        CommonResult<List<BargeRotationRespVO>> commonResult;
        try {
            commonResult = bargeRotationApi.list(bargeQueryReqDTO);
        } catch (Exception e) {
            log.error("caught an exception on queryBargeRotation", e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_BARGE_ROTATION_EXCEPTION);
        }
        return commonResult;
    }

    @Override
    public void insertBargeRotation(BargeRotationCreateDTO bargeRotationCreateDTO) {
        CommonResult<Boolean> commonResult;
        try {
            commonResult = bargeRotationApi.insert(bargeRotationCreateDTO);
        } catch (Exception e) {
            log.error("caught an exception on insertBargeRotation", e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.INSERT_BARGE_ROTATION_EXCEPTION);
        }

        if (commonResult == null || commonResult.getData() == null || commonResult.getData() == false) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.INSERT_BARGE_ROTATION_FAILED);
        }
    }

    @Override
    public String getBargeVesselCode(String name, String partnerCode, String bargeType) {
        TransportValidateReqDTO reqDTO = new TransportValidateReqDTO();
        reqDTO.setBargeType(bargeType);
        TransportReqDTO transportReq = new TransportReqDTO();
        transportReq.setPartnerCode(partnerCode);
        transportReq.setTransportName(name);
        List<TransportReqDTO> dtoList = new ArrayList<>();
        dtoList.add(transportReq);
        reqDTO.setDtoList(dtoList);
        CommonResult<List<TransportValidateRespDTO>> commonResult;
        try {
            commonResult = bargeRotationApi.validateAndGetCode(reqDTO);
        } catch (Exception e) {
            log.error("caught an exception on getBargeVesselCode", e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_VESSEL_CODE_EXCEPTION);
        }

        if (commonResult == null || CollectionUtils.isEmpty(commonResult.getData())) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_VESSEL_CODE_EMPTY);
        }
        return commonResult.getData().get(0).getTransportCode();
    }

    @Override
    public BargePolAndPodRespDTO getBargePolAndPod(BargePolPodReqDTO reqDto) {
        CommonResult<List<BargePolAndPodRespDTO>> commonResult;
        try {
            commonResult = bargeRotationApi.listPolAndPod(reqDto);
        } catch (Exception e) {
            log.error("caught an exception on getBargePolAndPod", e);
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_BARGE_POL_AND_POD_EXCEPTION);
        }

        if (commonResult == null || CollectionUtils.isEmpty(commonResult.getData())) {
            throw ServiceExceptionUtil.exception(ApiErrorCodeConstants.GET_BARGE_POL_AND_POD_EMPTY);
        }

        List<BargePolAndPodRespDTO> respList = commonResult.getData();
        return respList.stream().filter(resp -> resp.getPolRespDTO().getEnabled()).findFirst().orElse(null);
    }
}
